package com.cxsw.rms.controller;

import com.cxsw.rms.entity.Student;
import com.cxsw.rms.entity.SysUser;
import com.cxsw.rms.service.StudentService;
import com.cxsw.rms.service.SysUserService;
import com.cxsw.rms.utils.Constants;
import com.cxsw.rms.utils.DataUtils;
import com.cxsw.rms.utils.ResultObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;


/**
 * 注册控制器
 *
 * @author Han Fuhao
 * @date 2023/05/16
 */
@RestController
@RequestMapping
public class RegisterController {
    /**
     * 关于系统用户业务逻辑层Bean注入
     */
    @Resource
    private SysUserService sysUserService;
    /**
     * 关于学生业务逻辑层Spring注入
     */
    @Resource
    private StudentService studentService;
    /**
     * 注册及数据响应
     *
     * @param sysUser 系统用户
     * @return {@link String}
     */
    @PostMapping("register")
    public ResultObject register(@RequestBody SysUser sysUser){
        return sysUserService.register(sysUser);
    }

    /**
     * 注册学生
     *
     * @param student 学生
     * @param session 会话
     * @return {@link Student}
     */
    @PostMapping("student")
    public ResultObject registerStudent(@RequestBody Student student, HttpSession session) throws IOException {
        byte[] fileData = (byte[]) session.getAttribute(Constants.SESSION_USER_IMG);
        if (fileData != null){
            student.setBirthday(student.getBirthday());
            student.setPhotoPath(student.getName() + student.getPhoneNumber());
            student.setCreateTime(DataUtils.formatDateTime(new Date()));
            student.setUpdateTime(DataUtils.formatDateTime(new Date()));
            return studentService.registerStudent(student, session);
        }
        return ResultObject.failure("请上传照片");
    }

    /**
     * 学生照片接收
     *
     * @param file    文件
     * @param session 会话
     * @return {@link ResultObject}
     * @throws IOException ioexception
     */
    @RequestMapping("studentImg")
    public ResultObject studentImg(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        if (file != null){
            byte[] fileData = file.getBytes();
            session.setAttribute(Constants.SESSION_USER_IMG, fileData);
            return ResultObject.success("上传成功！", null);
        }
        else {
            return ResultObject.failure("上传失败！");
        }
    }
}
